﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;

namespace Dycox.Windows.Forms
{
    public class DetailsViewInstanceItem : DetailsViewItem
    {
        public DetailsViewInstanceItem(object instance)
            : base(string.Empty)
        {
            if (instance != null)
            {
                var coll = TypeDescriptor.GetProperties(instance, Attributes);
                _expandable = coll.Count > 0;
            }

            _instance = instance;

            ItemText = GetText();
        }

        protected virtual string GetText()
        {
            return GetObjectText(_instance);
        }

        internal static string GetObjectText(object inst)
        {

            if (inst != null)
            {
                var method = inst.GetType().GetMethod("ToString",
                    System.Reflection.BindingFlags.DeclaredOnly | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public,
                    null, Type.EmptyTypes, null);

                if (method != null) return inst.ToString();

            }

            return string.Empty;
        }

        private object _instance;

        public object Instance
        {
            get { return _instance; }
        }

        bool _expandable;

        public override bool Expandable
        {
            get
            {
                return _expandable;
            }
        }

        protected override void PopulateItems(List<DetailsViewItem> list)
        {
            foreach (PropertyDescriptor p in TypeDescriptor.GetProperties(_instance, Attributes))
            {
                list.Add(DetailsViewItem.CreateItem(p, _instance));
            }
        }
    }
}
